package com.lkd.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SupplyTaskJob {
    @Autowired
    private VendingMachineService vendingMachineService;


    @XxlJob("supplyAllVmsTask")
    public ReturnT<String> supplyTsak(String param) throws Exception{
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        int total = shardingVo.getTotal();
        int index = shardingVo.getIndex();
        log.info("分片参数 当前分片参数{} 总分片索引" + index,total);
        XxlJobLogger.log("分片参数 当前分片参数{} 总分片索引" + index,total);
        //System.out.println("下想想");
        //获取所有运行状态的售货机innercode
        List<VendingMachineEntity> runningVmList = vendingMachineService.list(Wrappers
                .<VendingMachineEntity>lambdaQuery()
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id," + total + ") =" + index));
        List<String> runningInnerCode = runningVmList.stream().map(VendingMachineEntity::getInnerCode).collect(Collectors.toList());
     if (CollectionUtils.isNotEmpty(runningInnerCode)){
         runningInnerCode.forEach(code->{
             XxlJobLogger.log("扫描售货机" + code);
             //调用售货机的自动创建补货工单的方法
             vendingMachineService.autoSupplySkuTask(code);
         });
     }

        return ReturnT.SUCCESS;
    }
}
